package com.afinal.intelligencetrash.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afinal.intelligencetrash.R;
import com.afinal.intelligencetrash.global.GlobalEnvironment;
import com.afinal.intelligencetrash.ui.base.AbstractBaseToolbarCoreActivity;
import com.afinal.intelligencetrash.ui.fragment.InfromationTask;
import com.afinal.intelligencetrash.ui.fragment.SettingTask;
import com.afinal.intelligencetrash.ui.fragment.TrashRTStatusTask;
import com.afinal.intelligencetrash.ui.fragment.interfaces.FragmentView;
import com.afinal.intelligencetrash.utils.SimpleUtil;

import org.zackratos.ultimatebar.UltimateBar;

import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;


public class MainActivity extends AbstractBaseToolbarCoreActivity implements  NavigationView.OnNavigationItemSelectedListener{

    @BindView(R.id.drawer) DrawerLayout drawer = null;
    @BindView(R.id.nav_view) NavigationView nav_view = null;
    private RelativeLayout nav_header = null;
    private Menu nav_menu;

    private HashMap<Integer, FragmentView> fragmentHolder = new HashMap<>();
    private static HashMap<Integer, Class<? extends FragmentView>> fragmentClazzHolder = new HashMap<>(5);
    static {
        fragmentClazzHolder.put(R.id.menu_item_infrom, InfromationTask.class);
        fragmentClazzHolder.put(R.id.menu_item_trash_data, TrashRTStatusTask.class);
        fragmentClazzHolder.put(R.id.menu_item_setting, SettingTask.class);
    }
    @Override
    protected boolean launchCheck() {
        boolean isLogined = GlobalEnvironment.haveLogined();
        if(!isLogined){
            LoginActivity.launchActivity(this);
        }
        return isLogined;
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        nav_header = (RelativeLayout) nav_view.getHeaderView(0);
        nav_menu = nav_view.getMenu();

        int[][] state = new int[][]{new int[]{-android.R.attr.state_checked}, new int[]{android.R.attr.state_checked}};
        int[] colors = new int[]{getResources().getColor(R.color.menu_item_normal), getResources().getColor(R.color.menu_item_checked)};
        ColorStateList colorStateList = new ColorStateList(state, colors);
        nav_view.setItemTextColor(colorStateList);
        nav_view.setItemIconTintList(colorStateList);
        nav_view.setNavigationItemSelectedListener(this);
    }

    @Override
    protected void initData() {
        TextView tv_username = (TextView) nav_header.findViewById(R.id.tv_username);
        tv_username.setText(GlobalEnvironment.currentUser.getUsername());

        int size = nav_menu.size();
        int defaultCheckedItemId = -1;
        for (int i=0; i < size; i++){
            MenuItem item = nav_menu.getItem(i);
            if(item.isChecked()){
                defaultCheckedItemId = item.getItemId();
                break;
            }
        }
        if(defaultCheckedItemId != -1){
            loadFragmentViewById(defaultCheckedItemId);
        }
    }

    private void loadFragmentViewById(int checkedItemId) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        hideAllFragmentView(transaction);

        FragmentView fragment = fragmentHolder.get(checkedItemId);
        if(fragment == null){
            Class<? extends FragmentView> clazz = fragmentClazzHolder.get(checkedItemId);
            fragment = refectFragmentViewInstance(clazz);
            transaction.add(R.id.container, (Fragment) fragment, new Integer(checkedItemId).toString());
        }
        transaction.show((Fragment) fragment);
        transaction.commit();
        setToolbarTitle(nav_menu.findItem(checkedItemId).getTitle().toString());

    }

    private void hideAllFragmentView(FragmentTransaction transaction) {
        for(Map.Entry<Integer, FragmentView> temp : fragmentHolder.entrySet()){
            Fragment fragment = (Fragment) temp.getValue();
            if(fragment != null){
                transaction.hide(fragment);
            }
        }
    }

    private FragmentView refectFragmentViewInstance(Class<? extends FragmentView> clazz) {
        FragmentView temp = null;
        try {
            temp = clazz.newInstance();
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        return temp;
    }


    @Override
    protected int getLayoutResId() {
        return R.layout.activity_main;
    }

    @Override
    protected String getToolbarTitle() {
        return "";
    }

    @Override
    protected boolean isDisplayHomeAsUpEnabled() {
        return true;
    }

    @Override
    protected void dealloc() {
        if(!fragmentHolder.isEmpty()){
            fragmentHolder.clear();
        }
    }

    @Override
    protected int getNavToolbarLayoutResId() {
        return 0;
    }

    @Override
    protected int getToolbarHomeAsUpIcon() {
        return R.drawable.menu_icon;
    }

    @Override
    protected void OnToolbarHomeAsUpClick(View v) {

        drawer.openDrawer(GravityCompat.START);
    }

    public static void launchActivity(Context context){
        Intent intent = new Intent(context, MainActivity.class);
        context.startActivity(intent);
    }

    /*
    *  双击返回键退出
    * */
    private long lastBackPress = 0;
    @Override
    public void onBackPressed() {
        if(drawer.isDrawerOpen(GravityCompat.START)){
            drawer.closeDrawer(GravityCompat.START);
            return;
        }
        long thisBackPress = System.currentTimeMillis();
        if(thisBackPress - lastBackPress > 2000){
            SimpleUtil.showToast(this, "再按一次退出程序~");
            lastBackPress = thisBackPress;
        }else {
            finish();
            super.onBackPressed();
        }
    }

    @Override
    protected void initSystemBar() {
        UltimateBar ultimateBar = new UltimateBar(this);
        ultimateBar.setColorBarForDrawer(getResources().getColor(R.color.colorPrimary), 0);
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
//        SimpleUtil.showToast(this, item.getTitle().toString());
        if(item.isChecked()){
            return true;
        }
        loadFragmentViewById(item.getItemId());
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}
